//
//  ChangeUserViewController.m
//  yunyan
//
//  Created by Shui on 2018/5/3.
//  Copyright © 2018年 haichuang. All rights reserved.
//

#import "ChangeUserViewController.h"
#import "CZHDatePickerView.h"
#import "DatePickerHeader.h"
#import "RegisterViewController.h"

@interface ChangeUserViewController ()<UINavigationControllerDelegate>{
    
    NSString * _chooseType;
    NSData *  imageData;
}
@property (weak, nonatomic) IBOutlet UIButton *userImageBtn;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UILabel *nexLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *birthdayLabel;

@end

@implementation ChangeUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
     [self customNaviItemTitle:@"修改个人资料" isLeft:YES];
    [self customTabBarButtonTitle:@"完成" image:nil target:self action:@selector(rightButtonEvent) isLeft:NO];
    
    _userImageBtn.layer.cornerRadius = 27.5f;
    _userImageBtn.layer.masksToBounds = YES;
    
    if (self.userDic) {
        
        [_userImageBtn sd_setBackgroundImageWithURL:ImageUrl(self.userDic[@"head_url"]) forState:UIControlStateNormal  placeholderImage:ImageName(@"img_head_portrait_pre")] ;
        _userName.text = self.userDic[@"user_nick"];
        if ([self.userDic[@"user_sex"]  integerValue]==0) {
            _nexLabel.text = @"女";
        }else {
             _nexLabel.text = @"男";
        }
        _phoneLabel.text =  self.userDic[@"mobile"];
        _birthdayLabel.text = self.userDic[@"birthday"];
    }

}

-(void)rightButtonEvent{
    
    if (_userName.text.length<=0||_userName.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请输入昵称");
        return;
    }
    if (_nexLabel.text.length<=0||_nexLabel.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请选择性别");
        return;
    }
    if (_birthdayLabel.text.length<=0||_birthdayLabel.text==nil) {
        
        SHuiMBhudTextTimeStr(@"请选择生日");
        return;
    }
    
    [self upDataRequest];
}

- (IBAction)changeImageBtnClick:(id)sender {
    [_userName resignFirstResponder];

    [BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
        if (image) {
            
            _chooseType = @"1";
            [_userImageBtn setBackgroundImage:image forState:UIControlStateNormal];
            
            imageData = UIImageJPEGRepresentation(image, 0.4);
            
            
            NSData *data = UIImageJPEGRepresentation(image, 0.5);
            NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            NSString * imageStr = [NSString stringWithFormat:@"data:image/png;base64,%@",encodedImageStr];
            
            NSLog(@"imageStr = %@",imageStr);
            
            [self upIconImageRequestFor:imageStr];
            
            USER_DEFAULTSet(imageData, @"chooseIconImage");
        }
    }];
    
}
- (IBAction)nexBtnClick:(id)sender {
    
        zySheetPickerView * pickerView = [zySheetPickerView ZYSheetStringPickerWithTitle:@[@"男",@"女"] andHeadTitle:@"选择性别" Andcall:^(zySheetPickerView *pickerView, NSString *choiceString) {
    
            _nexLabel.text = choiceString;
            [pickerView dismissPicker];
        }];
        [pickerView show];
    
}
- (IBAction)phoneClick:(id)sender {
    
    NSString * str = self.userDic[@"mobile"];
    
    if (str.length>0) {
        SHuiMBhudTextTimeStr(@"您已经绑定手机号！");
    }else{
    RegisterViewController * registerVC = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registerVC animated:YES];
    }
    
}
- (IBAction)birthdayClick:(id)sender {
    
    CZHWeakSelf(self);
    [CZHDatePickerView sharePickerViewWithCurrentDate:self.birthdayLabel.text DateBlock:^(NSString *dateString) {
        CZHStrongSelf(self);
        self.birthdayLabel.text = dateString;
    }];
    
}

-(void)upDataRequest{
    
    NSString * sexStr;
    if ([_nexLabel.text isEqualToString:@"女"]) {
       sexStr = @"0";
    }else {
       sexStr = @"1";
    }

    NSDictionary * dic = @{@"token":USER_DEFAULTGet(@"token"),
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"birthday":self.birthdayLabel.text,
                           @"user_nick":_userName.text,
                           @"user_sex":sexStr
                           };


    [PostNetWorking postNetWorkingStr:RequestUrlStr(edit_userMessage_api) andparameters:dic Success:^(id responseObject) {
        
        SHuiMBhudTextTimeStr(@"提交成功！");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
            [self.navigationController popViewControllerAnimated:YES];
        });
     

    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {

        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;

        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else if(responses.statusCode == 403){
            SHuiMBhudTextTimeStr(@"认证失败");
        }else if (responses.statusCode == 502){
            SHuiMBhudTextTimeStr(@"昵称只能是汉字、字母和数字，最大长度为6");
        } else if (responses.statusCode == 500){
            
            SHuiMBhudTextTimeStr(@"最大上传1M的图片");
        }else {

            SHuiMBhudTextNetError;
        }
    }];

}

// 只有头像的
-(void)upIconImageRequestFor:(NSString *)dataStr {
    
    

    
    NSDictionary * dic = @{@"token":USER_DEFAULTGet(@"token"),
                           @"user_id":USER_DEFAULTGet(@"user_id"),
                           @"mac_code":[SHJudgeTools getDeviceId],
                           @"uploadType":@"3",
                           @"id":@"0",
                           @"img":dataStr
                           };

    [PostNetWorking postNetWorkingStr:RequestUrlStr(releas_image_api) andparameters:dic Success:^(id responseObject) {
        
        SHuiMBhudTextTimeStr(@"更新成功！");
       
    } failed:^(NSURLSessionDataTask * _Nullable task,NSError *error) {
        
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        
        if (responses.statusCode == 404) {
            SHuiMBhudTextTimeStr(@"未获取到数据");
        }else if(responses.statusCode == 403){
            SHuiMBhudTextTimeStr(@"认证失败");
        }else {
            
            SHuiMBhudTextNetError;
        }
    }];
}


@end
